package com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;

import com.beans.MenuInfo;
import com.jdbc.DBUtil;

public class MenuDao {

	// 根据父级菜单的ID,查询它的子级
	private List<MenuInfo> getMenuList(int parentId) {
		String sql = "select * from menuInfo where parentId=?";
		return DBUtil.getList(sql, MenuInfo.class, parentId);
	}

//	根据角色id查出整个菜单使用
	public List<MenuInfo> getMenuLists(int reloid) {
		String sql = "select * from menuinfo where id in (select menuId from rolemenu where roleId=?) and parentId=0";
		List<MenuInfo> oneMenuInfos = DBUtil.getList(sql, MenuInfo.class, reloid);
		for (MenuInfo i : oneMenuInfos) {
			String sql2 = "select * from menuInfo where id in (select menuId from rolemenu where roleId=?) and parentId=?";
			i.setTwoMenuInfos(DBUtil.getList(sql2, MenuInfo.class,reloid,i.getId()));
		}
		return oneMenuInfos;
	}

	// 获取全部menu菜单
	public List<MenuInfo> getAllMenus() {
		List<MenuInfo> oneMenuInfos = getMenuList(0);
		for (MenuInfo i : oneMenuInfos) {
			i.setTwoMenuInfos(getMenuList(i.getId()));
		}
		return oneMenuInfos;

	}

	// 获取角色对应的菜单编号
	public List<Integer> getRoleLists(int roleid) {
		String sql = "select menuId from rolemenu where roleId=?";
		List<Integer> ints = DBUtil.getListScalar(sql, roleid);
		return ints;
	}

	// 修改角色权限关系
	public int updateRoleMenu(int roleid, String[] menuLists) {
		int ins = 0;
		try {
			ins = DBUtil.update("delete from rolemenu where roleId= ?", roleid);
			PreparedStatement stm = null;
			try {
				Connection conn = DBUtil.getConn();
				String sql = "insert into rolemenu(roleId,menuId) values ( ?,?) ";
				stm = conn.prepareStatement(sql);

				for (String str : menuLists) {
					stm.setInt(1, roleid);
					stm.setString(2, str);
					stm.addBatch(); // 添到批处理中了
				}
				stm.executeBatch(); // 执行批处理

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				DBUtil.close(null, stm);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ins;
	}
}
